package com.bj.zspace.cat.controller;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 *
 * Cross: 跨边界访问维度
 *     client: type=PigeonCall/Call
 *             localAddress: tree.getIpAddress
 *             child: Event表示具体的内容
 *                Event:
 *                   type: PigeonCall.server/Call.server
 *                   name: RemoteAddress
 *                   ---------
 *                   type: PigeonCall.app/Call.app
 *                   name: App
 *                   ---------
 *                   type: PigeonCall.port/Call.port
 *                   name: clientPort
 *             RemoteRole: Pigeon.Server
 *             DetailType: PigeonCall
 *     Server: type=PigeonService/Service
 *             localAddress: tree.getIpAddress
 *             child: Event表示具体的信息
 *                 Event:
 *                    type: PigeonService.client/Service.client
 *                    name: remoteAddress
 *                    ----------
 *                    type: PigeonService.app/Service.app
 *                    name: app
 *             RemoteRole: Pigeon.Client
 *             DetailType: PigeonService
 *
 **/
@RestController
public class CrossTest {

    @GetMapping(value = "/cross/client")
    public String crossClient() {
        Cat.getManager().getThreadLocalMessageTree().setIpAddress("10.2.57.60");
        Transaction t = Cat.newTransaction("Call", "findOrder");
        try {
            TimeUnit.SECONDS.sleep(1);
            Cat.logEvent("Call.server", "10.2.57.100");
            Cat.logEvent("Call.app", "study-cat");
            Cat.logEvent("Call.port", "8080");
            int i = new Random().nextInt(2);
            if (i == 1) {
                throw new RuntimeException("client exception test");
            }
        } catch (Exception e) {
            t.setStatus(e);
        } finally {
            t.setStatus(Message.SUCCESS);
            t.complete();
        }


        return "ok";
    }

    @GetMapping(value = "/cross/server")
    public String crossServer() {
        Cat.getManager().getThreadLocalMessageTree().setIpAddress("10.2.57.100");
        Transaction t = Cat.newTransaction("Service", "findOrder");
        try {
            TimeUnit.SECONDS.sleep(1);
            Cat.logEvent("Service.client", "10.2.57.60");
            Cat.logEvent("Service.app", "service-cat");
            int i = new Random().nextInt(2);
            if (i == 1) {
                throw new RuntimeException("server exception test");
            }
        } catch (Exception e) {
            t.setStatus(e);
        } finally {
            t.setStatus(Message.SUCCESS);
            t.complete();
        }


        return "ok";
    }

}
